/*
 * Activiti Modeler component part of the Activiti project
 * Copyright 2005-2014 Alfresco Software, Ltd. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
/** Custom controller for the save dialog */
var CustomSaveModelCtrl = ['$rootScope', '$scope', '$http', '$route', '$location',
    function ($rootScope, $scope, $http, $route, $location) {

        var modelMetaData = $scope.editor.getModelMetaData();

        var json = $scope.editor.getJSON();
        if (json.properties.documentation == 'null') {
            json.properties.documentation = '';
        }
        var saveDialog = {
            'name': json.properties.name,
            'description': json.properties.documentation
        };

        $scope.saveDialog = saveDialog;

        json = JSON.stringify(json);

        /*var params = {
            modeltype: modelMetaData.model.modelType,
            json_xml: json,
            name: 'model'
        };*/

        $scope.status = {
            loading: false
        };


        $scope.isNotIE = true;
        /*因为ie保存操作后不会刷新页面，所以ie是屏蔽了保存按钮
         if (!!window.ActiveXObject || "ActiveXObject" in window){
            $scope.isNotIE = false;
        }*/

        $scope.close = function () {
            $scope.$hide();
        };

        $scope.saveAndClose = function () {
            $scope.save(function () {
                CloseWindow('ok');
            });
        };

        /**
         * 增加我的保存
         * isDeployNew为是否为发布新版本
         */
        $scope.saveAndDeploy = function () {
            $scope.save(function () {
                CloseWindow('ok');
            }, true);
        };


        $scope.save = function (successCallback, isDeployNew) {
            if (!$scope.saveDialog.name || $scope.saveDialog.name.length == 0) {
                return;
            }

            // Indicator spinner image
            $scope.status = {
                loading: true
            };

            modelMetaData.name = $scope.saveDialog.name;
            modelMetaData.description = $scope.saveDialog.description;

            var json = $scope.editor.getJSON();
            json.properties.name = $scope.saveDialog.name;
            json.properties.documentation = $scope.saveDialog.description;

            /**
             * 将"抄送人"和"审核可编辑"值添加到documentation中
             */
            var children = json.childShapes;
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                if (child.stencil.id == 'UserTask') {
                    var properties = child.properties;
                    v_ccpeople = 'ccs="";';
                    v_editableaudit = 'editable="";';
                    v_grade = 'grade="";';
                    v_relation = 'relation="";';
                    v_isassign = 'isassign="";';
                    v_isvalidate = 'isvalidate="";';
                    if (properties && properties.ccpeople) {
                        if (properties.ccpeople.assignment) {
                            v_ccpeople = 'ccs="' + properties.ccpeople.assignment.assignee + '";';
                        }
                    }
                    if (properties && properties.editableaudit) {
                        if (properties.editableaudit == '是') {
                            v_editableaudit = 'editable="1";';
                        } else {
                            v_editableaudit = 'editable="0";';
                        }
                    }
                    if (properties && properties.grade) {
                        v_grade = 'grade="' + properties.grade + '";';
                    }
                    if (properties && properties.relation) {
                        v_relation = 'relation="' + properties.relation + '";';
                    }
                    if (properties && properties.isassign) {
                        v_isassign = 'isassign="' + properties.isassign + '";';
                    }
                    if (properties && properties.isvalidate) {
                        v_isvalidate = 'isvalidate="' + properties.isvalidate + '";';
                    }
                    properties.documentation = v_ccpeople + v_editableaudit + v_grade + v_relation + v_isassign + v_isvalidate;
                }
            }

            json = JSON.stringify(json);
            var selection = $scope.editor.getSelection();
            $scope.editor.setSelection([]);

            // Get the serialized svg image source
            var svgClone = $scope.editor.getCanvas().getSVGRepresentation(true);
            $scope.editor.setSelection(selection);
            if ($scope.editor.getCanvas().properties["oryx-showstripableelements"] === false) {
                var stripOutArray = jQuery(svgClone).find(".stripable-element");
                for (var i = stripOutArray.length - 1; i >= 0; i--) {
                    stripOutArray[i].remove();
                }
            }

            // Remove all forced stripable elements
            var stripOutArray = jQuery(svgClone).find(".stripable-element-force");
            for (var i = stripOutArray.length - 1; i >= 0; i--) {
                stripOutArray[i].remove();
            }

            // Parse dom to string
            var svgDOM = DataManager.serialize(svgClone);

            var params = {
                actModelId: $scope.editor.id,
                jsonXml: json,
                svgXml: svgDOM,
                name: $scope.saveDialog.name,
                description: $scope.saveDialog.description,
                deployFlag: isDeployNew ? '1' : '0',
            };

            console.log(params);

            // 发布时校验
            if (params.deployFlag == '1') {
                var elements = $scope.editor.getJSON();
                if (elements.childShapes) {
                    if (elements.childShapes.length == 0) {
                        // 没有元素不能进行发布
                        $scope.errorMsg = '未编辑工作流元素，无法进行发布！';
                        return;
                    } else if (elements.childShapes.length > 0) {
                        // 如果有用户任务，则必须添加派遣值u sertaskassignment
                        var element = elements.childShapes;
                        for (var i = 0; i < element.length; i++) {
                            if (element[i].stencil.id == 'UserTask' && element[i].properties.usertaskassignment == "") {
                                $scope.errorMsg = '发布前必须给用户任务添加派遣值';
                                $scope.error = {};
                                $scope.status.loading = false;
                                return;
                            }
                        }
                    }
                }
            }
            let model1 = JSON.parse(modelMetaData.string);
            //todo Update
            $http({
                method: 'PUT',
                data: params,
                ignoreErrors: true,
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                transformRequest: function (obj) {
                    var str = [];
                    for (var p in obj) {
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    }
                    return str.join("&");
                },
                url: KISBPM.URL.putModel(model1.modelId)
            }).success(function (data, status, headers, config) {
                $scope.editor.handleEvents({
                    type: ORYX.CONFIG.EVENT_SAVED
                });
                $scope.modelData.name = $scope.saveDialog.name;
                // $scope.modelData.lastUpdated = data.lastUpdated;

                $scope.status.loading = false;
                $scope.$hide();

                // Fire event to all who is listening
                var saveEvent = {
                    type: KISBPM.eventBus.EVENT_TYPE_MODEL_SAVED,
                    model: params,
                    modelId: model1.modelId,
                    eventType: 'update-model'
                };
                KISBPM.eventBus.dispatch(KISBPM.eventBus.EVENT_TYPE_MODEL_SAVED, saveEvent);

                // Reset state
                $scope.error = undefined;
                $scope.status.loading = false;

                // Execute any callback
                if (successCallback) {
                    successCallback();
                } else {
                    if (model1.modelId === data) {
                        window.location.reload();
                    } else {
                        var searchUrl = window.location.search;
                        var arr = searchUrl.split("&");
                        var _searchUrl = "";
                        for (var i = 0; i < arr.length; i++) {
                            if (arr[i].startsWith("modelId")) {
                                _searchUrl = _searchUrl + "modelId=" + data + "&";
                            } else {
                                _searchUrl = _searchUrl + arr[i] + "&";
                            }
                        }
                        window.location.href = "modeler.html" + _searchUrl + "t=" + Math.random();
                    }
                }
            }).error(function (data, status, headers, config) {
                $scope.error = {};
                $scope.errorMsg = '存在重复名称的元素，无法发布工作流！';
                console.log('Something went wrong when updating the process model:' + JSON.stringify(data));
                $scope.status.loading = false;
            });
        };

    }];
